<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Auth_model extends CI_Model
{
   public function __construct()
   {
    parent::__construct();
   }

   //Hàm kiểm tra username hoặc password đã tồn tại chưa
   public function checkUserRegister($username){
   	  $query = "select username from auth_users where username = :u";
   	  $st = $this->db->prepare($query);
   	  $st->bindValue(':u',$username);
      $st->execute();
      $num_rows = $st->rowCount();
      $st->closeCursor();
    
      return $num_rows;
   }
   public function checkEmailRegister($email){
   	  $query = "select username from auth_users where email = :mail";
   	  $st = $this->db->prepare($query);
   	  $st->bindValue(':mail',$email);
      $st->execute();
      $num_rows = $st->rowCount();
      $st->closeCursor();
    
      return $num_rows;
   }

   //Hàm chèn dữ liệu sau khi người dùng đăng ký
   function insert_user($arr)
  {
    $key = array();
    $value = array();
    foreach ($arr as $k => $v) {
        $key[] = $k;
        $value[] = $v;
      }  
    $sql = "INSERT INTO auth_users (".$key[0].",".$key[1].",".$key[2].",".$key[3].",".$key[4].",".$key[5].",".$key[6].",".$key[7].",".$key[8].",".$key[9].",".$key[10].",".$key[11].") VALUES ('".$value[0]."','".$value[1]."','".$value[2]."','".$value[3]."','".$value[4]."','".$value[5]."','".$value[6]."','".$value[7]."','".$value[8]."','".$value[9]."','".$value[10]."','".$value[11]."')";
    
    $stmt = $this->db->prepare($sql);
    $stmt->execute();
    $stmt->closeCursor();
    //return $this->db->lastInserId();
  }

  //Hàm xử lý đăng nhập
  function getLogin($u,$p)
  {
    $query = 'select * from auth_users where ((username = :u or email = :mail) and password = :p)';
    $stmt = $this->db->prepare($query);
    $stmt->bindValue(':u',$u);
    $stmt->bindValue(':mail',$u);
    $stmt->bindValue(':p',$p);
    $stmt->execute();
    $row = $stmt->fetch(PDO::FETCH_ASSOC);
    $stmt->closeCursor();
    if(count($row) > 0) {
      return $row;
    }else 
      return false;
  }

  //Hàm lấy thông tin người dùng theo username
  function getInfoUser($u)
  {
  	$qr = 'select * from auth_users where username = :u';
  	$st = $this->db->prepare($qr);
  	$st->bindValue(':u',$u);
  	$rs = $st->fetchAll(PDO::FETCH_ASSOC);
  	$st->closeCursor();

    return $rs;
  }
}
